package com.zuoban.shiro;

import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.zuoban.common.Result;
import lombok.SneakyThrows;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

public class AuthFilter extends AuthenticatingFilter {

    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // 从header中获取token
        String token = request.getHeader("Authorization");
        return new AuthToken(token);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest httpServletRequest= (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse= (HttpServletResponse) servletResponse;
        httpServletResponse.setContentType("text/html;charset=utf-8");
        String token=httpServletRequest.getHeader("Authorization");
        if (StringUtils.isEmpty(token)){
            HashMap<String, Object> map = new HashMap<>();
            map.put("localRequestUrl",httpServletRequest.getRequestURL());
            Result result = new Result(HttpStatus.HTTP_NO_CONTENT, "在请求头中未发现token", map);
            httpServletResponse.getWriter().print(JSONUtil.toJsonStr(result));
            return false;
        }
        return executeLogin(servletRequest,servletResponse);
    }

    @SneakyThrows
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest= (HttpServletRequest) request;
        HttpServletResponse httpServletResponse= (HttpServletResponse) response;

        HashMap<String, Object> map = new HashMap<>();
        map.put("localRequestUrl",httpServletRequest.getRequestURL());
        Result result = new Result(HttpStatus.HTTP_NOT_AUTHORITATIVE, e.getMessage(), map);
        httpServletResponse.getWriter().print(JSONUtil.toJsonStr(result));
        return false;
    }

    // 所有请求全部拒绝访问 单独放行option请求
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return ((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name());
    }
}
